package com.wyc.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.ICaptcha;
import com.wyc.pojo.Allusers;
import com.wyc.pojo.MoveOut;
import com.wyc.pojo.OtherUserInformationDTO;
import com.wyc.pojo.UserBasicDTO;
import com.wyc.service.AllusersService;
import com.wyc.service.MoveOutService;
import com.wyc.service.UserBasicDTOService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Timestamp;
import java.time.Instant;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @ClassName UserController
 * @Author 王韫琛
 * @Date 2020/12/20 21:39
 * @Version 1.0
 */
@Controller
public class UserController {
    //controller调service层
    @Autowired
    private AllusersService allusersService;
    public String username;
    //用户输入的验证码判断
    @RequestMapping(value = ("login.action"))
    public String logins(HttpServletRequest request, HttpSession session, Model model, Allusers allusers) {
        username=allusers.getUsername();
        //取出用户输入的验证码
        String code = request.getParameter("pagerandom");
        //取出随机产生的验证码
        String checkcode = (String) session.getAttribute("checkcode");
        //获取前端权限放到数组中
        String permission = request.getParameter("permission");
        //进行比较
        if (!code.equalsIgnoreCase(checkcode)) {
            model.addAttribute("error", "验证码错误");
            //回到login
            return "/view/login";
        } else {
            if (permission.equals("超级管理员")) {
                if (allusersService.findUserByName(allusers.getUsername(), allusers.getPwd(), permission)) {
                    model.addAttribute("information", allusers.getUsername());
                    return "/view/superAdmin_jsp/super_admin";
                }
            } else if (permission.equals("普通管理员")) {
                if (allusersService.findUserByName(allusers.getUsername(), allusers.getPwd(), permission)) {
                    model.addAttribute("information", allusers.getUsername());
                    return "/view/admin_jsp/admin";
                }

            } else if (permission.equals("普通用户")) {
                if (allusersService.findUserByName(allusers.getUsername(), allusers.getPwd(), permission)) {
                    model.addAttribute("information", allusers.getUsername());
                    return "/view/user_jsp/user";
                }
            }

            model.addAttribute("login", "账户或密码错误");
            return "/view/login";
        }
    }
    //验证码获取
    @RequestMapping(value = "checkcode.action")
    public void checkCode(HttpServletResponse response, HttpSession session) throws IOException {
        //定义图形验证码得长度和宽度
        ICaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(100, 36,4,10);
        //将验证码存入session中
        session.setAttribute("checkcode", lineCaptcha.getCode());
        lineCaptcha.write(response.getOutputStream());
    }
    //超级管理员跳转到添加页面
    @RequestMapping("/toSuperAddPager")
    public String toSuperAddPager(){
        return "/view/superAdmin_jsp/addSuperUser";
    }
    //超级管理员添加用户的请求
    @RequestMapping("/addUser")
    @ResponseBody
    public String toSuperAddPager(Allusers allusers) {
        allusers.setAddtime(Timestamp.from(Instant.now()).toString());
        Map<String, Object> map = new HashMap<>();
        if (allusersService.addUser(allusers)>0){

            map.put("success",true);
            map.put("message","添加成功");

        }else {
            map.put("success",false);
            map.put("message","修改失败");
        }
        return cn.hutool.json.JSONUtil.toJsonStr(map);
    }
    //超级管理员添加成功后跳转到展示页面
    @RequestMapping("/selectSuper_2")
    public String selectSuper_2(){
        return "/view/superAdmin_jsp/selectSuper_2";
    }
    //跳转到超级管理员维护页面
    @RequestMapping("/selectSuper")
    public String selectSuper() {
        return "/view/superAdmin_jsp/selectSuper";
    }
    //查询全部用户，返回到超级管理员维护信息展示页面
    @RequestMapping("/allUser")
    @ResponseBody
    public String findPage(@RequestParam(defaultValue = "1") Integer pageNum,
                               @RequestParam(defaultValue = "10") Integer pageSize) {
        Map<String, Object> map = new HashMap<>();
        //调用service得到分页对象
        List<Allusers> pageInfo = allusersService.findPage(pageNum, pageSize);
        map.put("code",0);
        map.put("msg","");
        map.put("count",allusersService.getTotal());//总数量
        map.put("data",pageInfo);//数据列表
        System.out.println(pageInfo.toString());
        return cn.hutool.json.JSONUtil.toJsonStr(map);
    }
    //查询用户名是否存在
    @ResponseBody
    @RequestMapping("/queryUserName")
    public String queryUserName(String username){
        Map<String,Object> map = new HashMap<>();
        System.out.println(username);
        System.out.println(allusersService.queryUserName(username));
        if (allusersService.queryUserName(username)!=null){
            map.put("success",true);
            map.put("message","名字已存在,请重新输入");
        }else {
            map.put("success",false);
            map.put("message","可以使用");
        }
        return cn.hutool.json.JSONUtil.toJsonStr(map);
    }
    //查询身份证是否存在
    @ResponseBody
    @RequestMapping("/queryUserIdentityCard")
    public String queryUserIdentityCard(String identity_card){
        Map<String,Object> map = new HashMap<>();
        if (allusersService.queryUserIdentityCard(identity_card)!=null){
            map.put("success",true);
            map.put("message","身份证已存在,请重新输入");
        }else {
            map.put("success",false);
            map.put("message","可以使用");
        }
        return cn.hutool.json.JSONUtil.toJsonStr(map);
    }
    //超级管理员修改用户
    @RequestMapping("/superUpdateUser")
    @ResponseBody
    public String toSuperUpdateUser(Allusers allusers){
        allusers.setAddtime(Timestamp.from(Instant.now()).toString());
        Map<String, Object> map = new HashMap<>();
        if (allusersService.updateUser(allusers)>0){
            //添加成功跳转到用户信息展示界面
//            return "/view/superAdmin_jsp/selectSuper_2";
            map.put("success",true);
            map.put("message","修改成功");
        }else {
            map.put("success",false);
            map.put("message","修改失败");
        }
        return cn.hutool.json.JSONUtil.toJsonStr(map);

    }
    //超级管理员删除用户
    @RequestMapping("/superDeleteById")
    @ResponseBody
    public String deleteById(Integer id){
        Map<String,Object> map = new HashMap<String,Object>();
        if (allusersService.deleteById(id)>0){
            map.put("success",true);
            map.put("message","删除成功");
        }else {
            map.put("success",false);
            map.put("message","删除失败");
        }
        return cn.hutool.json.JSONUtil.toJsonStr(map);
    }
    //普通管理员用户信息展示界面
    @RequestMapping("/admin")
    public String admin(){
        return "/view/admin_jsp/user_information";
    }
    //普通管理员查询入住用户
    @RequestMapping("/admin_Select_In")
    public String admin_Select_In(){
        return "/view/admin_jsp/user_selectInformation";
    }
    //查询入住信息
    @RequestMapping("/admin_Query_Id_Card")
    public String admin_Query_Id_Card(String identity_card,Model model){
        Allusers allusers = allusersService.queryUser(identity_card);
        List<Allusers> list = new ArrayList<Allusers>();
        list.add(allusers);
        System.out.println(list.toString());
        model.addAttribute("list",list);
        if(allusers==null){
            model.addAttribute("error","未查到用户");
        }else {
            model.addAttribute("error2","已查到,点我注册！");
        }
        return  "/view/admin_jsp/user_selectInformation";
    }
    //退出功能
    @RequestMapping("/outLogin")
    public String outLogin(HttpSession session) {
        return "/view/login";
    }
    //返回用户修改密码界面
    @RequestMapping("/updatePassWord")
    public String updatePassWord(){
        return "/view/user_jsp/updatePassWord";
    }
    //返回超级管理员修改密码界面
    @RequestMapping("/superUpdatePassWord")
    public String superUpdatePassWord(){
        return "/view/superAdmin_jsp/superUpdatePassWord";
    }
    //返回普通管理员修改密码界面
    @RequestMapping("/adminUpdatePassWord")
    public String adminUpdatePassWord(){
        return "/view/admin_jsp/adminUpdatePassWord";
    }
    //返回普通用户基本信息界面
    @RequestMapping("/basicData")
    public String basicData(){
        return "/view/user_jsp/basicData";
    }
    //返回超级管理员基本信息界面
    @RequestMapping("/superBasicData")
    public String superBasicData(){
        return "/view/superAdmin_jsp/superBasicData";
    }
    //返回普通管理员基本信息界面
    @RequestMapping("/adminBasicData")
    public String adminBasicData(){
        return "/view/admin_jsp/adminBasicData";
    }
    //用户修改密码
    @RequestMapping("/userUpdatePwd")
    @ResponseBody
    public String userUpdatePwd(String pwd,String newpwd){
        System.out.println(username);
        Map<String,Object> map = new HashMap<String,Object>();
        if (allusersService.userUpdatePdw(pwd, newpwd,username)>0){
            map.put("success",true);
            map.put("message","修改成功,可以继续操作，下次登录记得使用新密码哦！");
        }else {
            map.put("success",false);
            map.put("message","修改失败,旧密码不正确");
        }
        return cn.hutool.json.JSONUtil.toJsonStr(map);
    }
    @RequestMapping("/basicDataInformation")
    @ResponseBody
    //用户查看基本信息
    public String basicDataInformation(){
        Map<String, Object> map = new HashMap<>();
        Allusers allusers = allusersService.basicData(username);
        List<Allusers> list = new ArrayList<Allusers>();
        list.add(allusers);
        map.put("code",0);
        map.put("msg","");
        map.put("count",1);//总数量
        map.put("data",list);//数据列表
        return cn.hutool.json.JSONUtil.toJsonStr(map);
    }
    //普通用户忘记密码
    @RequestMapping("/allUserForgetPwd")
    public String allUserForgetPwd(){
        return "/view/user_jsp/allUserForgetPwd";
    }
    //所有用户忘记密码
    @RequestMapping("/allUserUpdatePwd")
    @ResponseBody
    public String allUserUpdatePwd(String username,String identity_card,String newpwd){
        System.out.println(username + identity_card + newpwd);
        System.out.println(allusersService.allUserUpdatePwd(username, identity_card, newpwd));
        Map<String,Object> map = new HashMap();
        if (allusersService.allUserUpdatePwd(username, identity_card, newpwd)>0){
            map.put("success",true);
            map.put("message","修改成功,去登录界面登录吧！");
        }else {
            map.put("success",false);
            map.put("message","修改失败,请重修修改！");
        }
        return cn.hutool.json.JSONUtil.toJsonStr(map);
    }
    //普通管理员获取住户信息
    @RequestMapping("/adminfFndInforPage")
    @ResponseBody
    public String adminfFndInforPage(@RequestParam(defaultValue = "1") Integer pageNum,
                           @RequestParam(defaultValue = "10") Integer pageSize) {
        String permission="超级管理员";
        Map<String, Object> map = new HashMap<>();
        //调用service得到分页对象
        List<Allusers> pageInfo = allusersService.adminfFndInforPage(pageNum, pageSize,permission);
        map.put("code",0);
        map.put("msg","");
        map.put("count",allusersService.adminGetInforTotal(permission));//总数量
        map.put("data",pageInfo);//数据列表
        System.out.println(pageInfo.toString());
        return cn.hutool.json.JSONUtil.toJsonStr(map);
    }
    //跳转到用户信息浏览界面
    @RequestMapping("/userInformationBasic")
    public String userInformationBrowsing(){
        return "/view/user_jsp/userInformationBrowsing";
    }

    @Autowired
    UserBasicDTOService userBasicDTOService;
    //查询当前用户的所有信息
    @RequestMapping("/UserBasicInformation")
    @ResponseBody
    public String findUserList(){
        System.out.println(username);
        Map<String, Object> map = new HashMap<>();
        System.out.println(username);
        System.out.println(userBasicDTOService.USER_BASIC_DTO(username));
        UserBasicDTO userBasicDTO = userBasicDTOService.USER_BASIC_DTO(username);
        List<UserBasicDTO> list = new ArrayList<>();
        list.add(userBasicDTO);
        map.put("code",0);
        map.put("msg","");
        map.put("count",1);//总数量
        map.put("data",list);//数据列表
        return cn.hutool.json.JSONUtil.toJsonStr(map);
    }
    //返回到用户其他信息界面
    @RequestMapping("/OtherUserInformation")
    public String OtherUserInformation(){
        return "/view/user_jsp/OtherUserInformation";
    }
    //查看用户其他信息
    @RequestMapping("/OtherUserInformationDTO")
    @ResponseBody
    public String OtherUserInformationDTO(){
        Map<String, Object> map = new HashMap<>();
        System.out.println(userBasicDTOService.OTHER_USER_INFORMATION_DTO(username));
        OtherUserInformationDTO otherUserInformationDTO = userBasicDTOService.OTHER_USER_INFORMATION_DTO(username);
        List<OtherUserInformationDTO> list = new ArrayList<>();
        list.add(otherUserInformationDTO);
        map.put("code",0);
        map.put("msg","");
        map.put("count",1);//总数量
        map.put("data",list);//数据列表
        return cn.hutool.json.JSONUtil.toJsonStr(map);
    }
    //跳转到用户迁出界面
    @RequestMapping("/userMoveOut")
    public String userMoveOut(){
        return "/view/user_jsp/userMoveOut";
    }
    //跳转到用户查看提交申请界面
    @RequestMapping("/userMoveOutDisplay")
    public String userMoveOutDisplay(){
        return "/view/user_jsp/userMoveOutDisplay";
    }
    //用户查看提交的信息
    @Autowired
    MoveOutService moveOutService;
    @ResponseBody
    @RequestMapping("/moveOut")
    public String moveOut(){
        System.out.println(username);
        Map<String, Object> map = new HashMap<>();
        MoveOut moveOut = moveOutService.moveOut(username);
        System.out.println(moveOutService.moveOut(username).toString());
        List<MoveOut> list = new ArrayList<>();
        list.add(moveOut);
        map.put("code",0);
        map.put("msg","");
        map.put("count",1);//总数量
        map.put("data",list);//数据列表
        return cn.hutool.json.JSONUtil.toJsonStr(map);
    }
    //一键删除所用用户信息
    @ResponseBody
    @RequestMapping("/deleteAllInfo")
    public String deleteAllInfo(String identity_card){
        System.out.println(identity_card);
        Map<String,Object> map = new HashMap<String,Object>();
        if (moveOutService.deleteByAdminIdentityCard(identity_card)>0&&moveOutService.deleteBySuperIdentityCard(identity_card)>0&& moveOutService.deleteByUserIdentityCard(identity_card)>0){
            map.put("success",true);
            map.put("message","删除成功");
        }else {
            map.put("success",false);
            map.put("message","删除失败，请逐步删除");
        }
        return cn.hutool.json.JSONUtil.toJsonStr(map);
    }
    //超级管理员修改用户迁出信息
    @ResponseBody
    @RequestMapping("/superAdminUpdateInformation")
    public String superAdminUpdateInformation(MoveOut moveOut){
        moveOut.setAddtime(Timestamp.from(Instant.now()).toString());
        Map<String, Object> map = new HashMap<>();
        if (moveOutService.superUpdateMoveInfo(moveOut)>0){
            map.put("success",true);
            map.put("message","提交成功");
        }else {
            map.put("success",false);
            map.put("message","提交失败");
        }
        return cn.hutool.json.JSONUtil.toJsonStr(map);
    }
    //检查身份证与当前用户注册时候的是否一样
    @RequestMapping("/SuperSelectByIdentity")
    @ResponseBody
    public String SuperSelectByIdentity(String identity_card){
        Map<String, Object> map = new HashMap<>();
        if (allusersService.SuperSelectByIdentity(identity_card,username)!=null){
            map.put("success",true);
            map.put("message","符合条件");
        }else {
            map.put("success",false);
            map.put("message","与注册时身份证不符");
        }
        return cn.hutool.json.JSONUtil.toJsonStr(map);
    }
    //检查当前登录的用户名与输入的用户名是否一致
    @RequestMapping("/SuperSelectByUsername")
    @ResponseBody
    public String SuperSelectByUsername(){
        Map<String, Object> map = new HashMap<>();
        if (allusersService.SuperSelectByUsername(username)!=null){
            map.put("success",true);
            map.put("message","与当前登录用户名一致");
        }else {
            map.put("success",false);
            map.put("message","与当前登录用户名不一致");
        }
        return cn.hutool.json.JSONUtil.toJsonStr(map);
    }

    //超级管理员根据身份证查询用户信息
    @RequestMapping("/SuperSelectByIdentityCard")
    @ResponseBody
    public String SuperSelectByIdentityCard(String identity_card){
        Allusers superSelectByIdentityCard = allusersService.SuperSelectByIdentityCard(identity_card);
        Map<String,Object> map = new HashMap<>();
        List<Allusers> list = new ArrayList<>();
        list.add(superSelectByIdentityCard);
        map.put("code",0);
        map.put("msg","");
        map.put("count",1);//总数量
        map.put("data",list);//数据列表
        return cn.hutool.json.JSONUtil.toJsonStr(map);
    }

    //去超级管理员界面
    @RequestMapping("/auto")
    public String auto (){
        return "/view/superAdmin_jsp/super_admin";
    }
    @RequestMapping("/domesticInquiry")
    public String domesticInquiry(){
        return "/view/superAdmin_jsp/domesticInquiry";
    }
}
